<template>
    <div class="container">
        <div class="query-box">
            <el-form ref="queryFormRef" :inline="true" :model="queryForm" class="demo-form-inline">
                <el-form-item label="商品名称">
                    <el-input v-model="queryForm.name" placeholder="商品名称" clearable />
                </el-form-item>
                <el-form-item label="是否上架">
                    <!-- <el-input v-model="queryForm.gender" placeholder="用户性别" clearable /> -->
                    <el-select
                        v-model="queryForm.isUp"
                        placeholder="是否上架"
                        style="width: 190px;"
                        >
                        <el-option label="全部" :value="null"></el-option>
                        <el-option
                            v-for="item in offNoOptions"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value"
                        />
                    </el-select>
                </el-form-item>
                <el-form-item label="是否推荐">
                    <!-- <el-input v-model="queryForm.gender" placeholder="用户性别" clearable /> -->
                    <el-select
                        v-model="queryForm.isRecommend"
                        placeholder="是否推荐"
                        style="width: 190px;"
                        >
                        <el-option label="全部" :value="null"></el-option>
                        <el-option
                            v-for="item in offNoOptions"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value"
                        />
                    </el-select>
                </el-form-item>
                <el-form-item label="商品状态">
                    <!-- <el-input v-model="queryForm.status" placeholder="用户状态" clearable /> -->
                     <el-select
                        v-model="queryForm.status"
                        placeholder="商品状态"
                        style="width: 190px;"
                        >
                        <el-option label="全部" :value="null"></el-option>
                        <el-option
                            v-for="item in statusOptions"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value"
                        />
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-button type="success" @click="onSearch">查询</el-button>
                    <el-button @click="onSearchReset">重置</el-button>
                </el-form-item>
            </el-form>
        </div>
        <div class="func-box">
             <el-row :gutter="10">
                <el-col :span="0.5"><el-button type="primary" plain @click="onSave()">新增</el-button></el-col>
                <el-col :span="0.5"><el-button type="success" plain :disabled="!isSingle" @click="onUpdate()">修改</el-button></el-col>
                <el-col :span="0.5"><el-button type="danger" plain :disabled="!(isSingle || isMultiple)" @click="onDelete()">删除</el-button></el-col>
            </el-row>
        </div>
        <div class="list-box">
             <el-table
                ref="tableRef"
                :data="listData"
                row-key="id"
                style="width: 100%"
                v-loading="loading"
                @selection-change="onSelectionChange"
            >
                <el-table-column type="selection" :selectable="selectable" width="55" />
                <el-table-column property="name" label="商品名称" />
                <el-table-column property="unitPrice" label="商品单价" />
                <el-table-column property="quantity" label="库存数量" />
                <el-table-column label="是否上架">
                    <template #default="scope">
                        {{ getOffNoLabel(scope.row.isUp) }}
                    </template>
                </el-table-column>
                <el-table-column label="是否推荐">
                    <template #default="scope">
                        {{ getOffNoLabel(scope.row.isRecommend) }}
                    </template>
                </el-table-column>
                <el-table-column label="商品状态">
                    <template #default="scope">
                        {{ getStatusLabel(scope.row.status) }}
                    </template>
                </el-table-column>
                <el-table-column fixed="right" label="操作" min-width="120">
                    <template #default="scope">
                        <el-button
                            link
                            type="primary"
                            size="small"
                            @click.prevent="onUpdate(scope.row, scope.$index)"
                        >
                            编辑
                        </el-button>
                        <el-button
                            link
                            type="primary"
                            size="small"
                            @click.prevent="onDeleteById(scope.row, scope.$index)"
                        >
                            删除
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>
        <!-- 分页功能区 -->
        <div class="block-box">
            <el-pagination
            v-model:current-page="current"
            v-model:page-size="pageSize"
            :page-sizes="[10, 20, 30, 50, 100, 200]"
            background
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="onChangeSize"
            @current-change="onChangePage"
            />
        </div>
        <!-- 表单弹窗 -->
      <el-dialog :title="title" draggable :overflow="true" v-model="visible" @close="onClose" width="65%">
        <div class="form-box">
          <el-form ref="formRef" :model="form" :rules="rules">
              <el-row>
                <el-col :span="8">
                  <el-form-item label="商品名称" prop="name">
                    <el-input v-model.trim="form.name" placeholder="商品名称"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="商品单价" prop="unitPrice">
                    <el-input v-model.trim="form.unitPrice" placeholder="商品单价"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="库存数量" prop="quantity">
                    <el-input v-model.trim="form.quantity" placeholder="库存数量"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="是否上架" prop="isUp">
                    <el-select v-model="form.isUp" placeholder="是否上架">
                      <el-option
                            v-for="item in offNoOptions"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value"
                        />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="是否推荐" prop="isRecommend">
                    <el-select v-model="form.isRecommend" placeholder="是否推荐">
                      <el-option
                            v-for="item in offNoOptions"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value"
                        />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="商品状态" prop="status">
                    <el-select v-model="form.status" placeholder="商品状态">
                      <el-option
                            v-for="item in statusOptions"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value"
                        />
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row justify="center">
                <el-col :span="4">
                  <el-form-item>
                    <!-- 在表单的提交按钮上添加 Vue 原生属性 native-type="submit" 可以让按钮变为表单提交按钮 -->
                    <el-button class="form-button" type="primary" native-type="submit" :loading="formLoading" @click="onSubmit">提交</el-button>
                    <el-button class="form-button" @click="onClose">取消</el-button>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
        </div>
      </el-dialog>
    </div>
</template>

<script setup>
import { ref, onBeforeMount } from 'vue'
import { byId, list, save, update, remove, batchRemove } from '@/api/shopping/goods'

// 额外功能

// 关键变量配置区
const moduleKey = '商品'

// 查询条件
const queryForm = ref({
    name: null,
    isUp: null,
    isRecommend: null,
    status: null,
    pageNumber: 1,
    pageSize: 10
})
const form = ref({ // 表单数据
  id: null,
  name: null,
  unitPrice: null,
  quantity: null,
  isUp: 1,
  isRecommend: 0,
  type: 1,
  status: 1
})
const rules = ref({ // 表单验证规则
  name: [{ required: true, message: '商品名称不能为空', trigger: 'blur' }],
  quantity: [{ required: true, message: '库存数量不能为空', trigger: 'blur' }],
  status: [{ required: true, message: '账号状态不能为空', trigger: 'blur' }],
})
/** 重置表单 */
function onResetForm() {
  if (visible.value) {
    formRef.value.resetFields()
  }
  form.value = {
    id: null,
    name: null,
    unitPrice: null,
    quantity: null,
    isUp: 1,
    isRecommend: 0,
    type: 1,
    status: 1
  }
}

// 下拉框数据区
const offNoOptions = [
    { label: '是', value: 1 },
    { label: '否', value: 0 },
]
const statusOptions = [
    { label: '可用', value: 1 },
    { label: '禁用', value: 0 }
]
/**
 * 获取状态标签
 * @param value 对应值 
 */
function getStatusLabel(value) {
    return statusOptions.find(item => item.value === value).label
}
/**
 * 获取是否类型标签
 * @param value 对应值
 */
function getOffNoLabel(value) {
    return offNoOptions.find(item => item.value === value).label
}


// 搜索功能区
const queryFormRef = ref()
/** 搜索 */
function onSearch() {
    list(queryForm.value).then(res => {
        disposeData(res)
    })
}
/** 重置 */
function onSearchReset() {
    queryFormRef.value.resetFields()
    onSearch()
}

// 操作功能区
/** 新增 */
function onSave() {
    title.value = `新增${moduleKey}`
    isUpdate.value = false
    visible.value = true
}
/**
 * 修改
 * @param {Object} row 所在行数据  
 * @param {Number} index 数据下标
 */
function onUpdate(row, index) {
    title.value = `修改${moduleKey}`
    isUpdate.value = true
    const id = row ? row.id : selectionIds.value[0]
    console.log(id, selectionIds.value[0])

    onResetForm()

    byId(id).then((res) => {
        if (res && res.code === 200) {
            form.value = res.data
            visible.value = true
        }
    })
}
/** 批量删除 */
function onDelete() {
    ElMessageBox.confirm(`是否删除${moduleKey}编号为 ${selectionIds.value} 的数据项?`, '提示', {
        distinguishCancelAndClose: true,
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        customClass: 'custom-message-box-style',
    }).then(() => {
        // 确认删除
        batchRemove(selectionIds.value).then((res) => {
        if (res && res.code === 200) {
            ElMessage({
                message: res.message,
                grouping: true,
                type: 'success',
            })
            onInit()
        } else {
            ElMessage({
                message: res.message,
                grouping: true,
                type: 'error',
            })
        }
        })
    }).catch(() => {
        // 取消删除
        ElMessage({
            message: '操作已取消',
            grouping: true,
            type: 'info'
        })
    })
}
/**
 * 单个删除
 * @param {Object} row 所在行数据  
 * @param {Number} index 数据下标
 */
function onDeleteById(row, index) {
    ElMessageBox.confirm(`是否删除${moduleKey}编号为 ${row.id} 的数据项?`, '提示', {
        distinguishCancelAndClose: true,
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        customClass: 'custom-message-box-style',
    }).then(() => {
        // 确认删除
        remove(row.id).then((res) => {
            if (res && res.code === 200) {
                ElMessage({
                    message: res.message,
                    grouping: true,
                    type: 'success',
                })
                onInit()
            } else {
                ElMessage({
                    message: res.message,
                    grouping: true,
                    type: 'error',
                })
            }
        })
    }).catch(() => {
        // 取消删除
        ElMessage({
            message: '操作已取消',
            grouping: true,
            type: 'info'
        })
    })
}

// 数据列表区
const loading = ref(false) // 列表加载状态
const listData = ref([]) // 列表数据
const selectionIds = ref([]) // 表格选中行数据ID
const isSingle = ref(false) // 是否选中单个的
const isMultiple = ref(false) // 是否选中多个的
/** 复选框变化 */
function onSelectionChange(val) {
  if (val.length > 1) {
    isSingle.value = false
    isMultiple.value = true
  } else if (val.length === 1) {
    isSingle.value = true
    isMultiple.value = true
  } else {
    isSingle.value = false
    isMultiple.value = false
  }
  selectionIds.value = val.map((item) => item.id)
}

// 分页功能区
const pageHide = ref(false) // 分页隐藏 当只有一页时
const pageSize = ref(8) // 分页每页数量
const total = ref(0) // 分页总数量
const current = ref(1) // 当前页码
/**
 * 每页数量变化
 * @param size 每页数量
 */
function onChangeSize(size) {
  pageSize.val = size
  queryForm.value.pageSize = size
  list(queryForm.value).then((res) => {
    disposeData(res)
  })
}
/**
 * 当前页码变化
 * @param page 页码
 */
function onChangePage(page) { // 分页页码改变
  queryForm.value.pageNumber = page
  current.value = page
  list(queryForm.value).then((res) => {
    disposeData(res)
  })
}

// 表单弹窗区
const title = ref('') // 弹窗标题
const visible = ref(false) // 弹窗显示状态
const isUpdate = ref(false) // 是否是修改
const formLoading = ref(false) // 表单加载状态
const formRef = ref()
/** 表单提交 */
function onSubmit() {
    formRef.value.validate((valid) => {
        formLoading.value = true
        if (form.value.id) {
            // 修改操作
            update(form.value).then((res) => {
                if (res && res.code === 200) {
                    ElMessage({
                        message: '修改成功',
                        grouping: true,
                        type: 'success',
                    })
                    onClose()
                    onInit()
                } else {
                    formLoading.value = false
                    ElMessage({
                        message: res.message,
                        grouping: true,
                        type: 'error',
                    })
                }
            }).catch(() => {
                formLoading.value = false
            })
        } else {
            // 新增操作
            save(form.value).then((res) => {
                if (res && res.code === 200) {
                    ElMessage({
                        message: '添加成功',
                        grouping: true,
                        type: 'success'
                    })
                    onClose()
                    onInit()
                } else {
                    formLoading.value = false
                    ElMessage({
                        message: res.message,
                        grouping: true,
                        type: 'error'
                    })
                }
            }).catch(() => {
                formLoading.value = false
            })
        }
    })
}
/** 关闭表单弹窗 */
function onClose() {
  formLoading.value = false
  visible.value = false
  onResetForm()
}


/** 列表数据处理 */
function disposeData(res) {
  if (res && res.code === 200) {
    loading.value = false
    listData.value = res.data.records
    total.value = res.data.total
    current.value = res.data.current
  } else {
    if (res) {
      ElMessage({
        message: res.message,
        grouping: true,
        type: 'error',
      })
    }
    loading.value = false
  }
}

/** 初始化函数 */
function onInit() {
  list(queryForm.value).then((res) => {
    disposeData(res)
  })
}

/** 页面渲染之前的生命周期函数 */
onBeforeMount(() => {
  onInit()
})
</script>

<style lang="scss" scoped>
.container {
    .query-box {
        margin-bottom: 20px;
    }
}
</style>